package utility

import (
	"net"
	"net/http"
	"strings"
)

//Proxy returns proxy client ips slice.
func Proxy(req *http.Request) []string {
	if ips := req.Header.Get("X-Forwarded-For"); ips != "" {
		return strings.Split(ips, ",")
	}
	return []string{}
}

// IP returns request client ip.
// if in proxy, return first proxy id.
// if error, return 127.0.0.1.
func Ip(req *http.Request) string {
	ips := Proxy(req)
	if len(ips) > 0 && ips[0] != "" {
		rip := strings.Split(ips[0], ":")
		return rip[0]
	}
	ip := strings.Split(req.RemoteAddr, ":")
	if len(ip) > 0 && ip[0] != "[" {
		return ip[0]
	}
	return "127.0.0.1"
}

// http://studygolang.com/articles/4465
func GetLocalIp() (string, error) {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return "", err
	}
	for _, a := range addrs {
		if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				return ipnet.IP.String(), nil
			}
		}
	}
	return "", nil
}
